<?php
namespace App\Services\Admin;

use App\Models\AdminUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class LoginService extends \App\Services\ComService
{
    /**
     * 后台管理员登陆处理
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request){
        $name = $request->post('name');
        $password = $request->post('password');

        $adminObject = AdminUser::where('name', '=', $name)->first();
        if(empty($adminObject)){
            return $this->responseError('用户名不存在');
        }
        $adminData = $adminObject->makeVisible(['password'])->toArray();

        if(!Hash::check($password, $adminData['password'], [$name, $password])){
            return $this->responseError('密码出错');
        }

        $password = Hash::make($password, [
            $name,
            $password,
        ]);
        $adminObject->password = $password;
        $adminObject->last_login_ip = $request->getClientIp();
        $adminObject->last_login_time = date('Y-m-d H:i:s');

        try{
            $adminObject->save();

            $request->session()->put('admin_user', [
                'id' => $adminData['id'],
                'name' => $adminData['name'],
                'is_administrator' => $adminData['is_administrator'],
                'expire_time' => time() + 9*60*60
            ]);

            return $this->responseSuccess();

        }catch (\Exception $e){
            return $this->responseError($e->getMessage());
        }

    }

    public function test(Request $request){
        return AdminUser::where('name', '=', 'ccc')->first();
    }

}
